<?php
/**
 * 小程序service
 * Created by PhpStorm.
 * User: xiaolihai
 * Date: 2020/10/12
 * Time: 下午7:27
 */
namespace App\Services;

use App\Models\PayResponseData;
use App\Models\SystemConfig;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Support\XML;
use Illuminate\Support\Facades\Log;


class MiniProgramService
{
    private static $instances = null;

    /**
     * 获取实例
     * @param $appType
     */
    public static function getApp($appType,$type='payment')
    {
        if (isset(self::$instances[$appType])) {
            return self::$instances[$appType];
        }

        $config = self::getConfig($appType,$type);

        $app = Factory::$appType($config);
        self::$instances[$appType] = $app;


        return $app;
    }

    /**
     * 获取参数配置
     * @param $appType
     * @return array
     */
    private static function getConfig($appType,$type='payment')
    {


        $wxapp = SystemConfig::select('config')->type(3)->first(); //获取小程序配置

        if($wxapp){
            $wxapp = $wxapp->config;
        }
        $config = [
            'response_type' => 'array',
        ];

        switch ($appType) {
            case 'miniProgram': //小程序配置
                $config['app_id'] = $wxapp['app_id'];
                $config['secret'] = $wxapp['secret'];
                break;
            case 'payment':
            case 'wxapp':
                $payment = SystemConfig::getByType(2);  //获取微信支付配置
                $notifyUrl = route('wechatwechat.notify');
                $config['mch_id'] = trim($payment['mch_id']);
                $config['key'] = trim($payment['apikey']);
                $config['cert_path'] = storage_path('app/' . $payment['cert_file']);
                $config['key_path'] = storage_path('app/' . $payment['key_file']);
                $config['notify_url'] = $notifyUrl;
                if($type == 'payment'){
                    $config['app_id'] = $wxapp['app_id'];
                }elseif($type == 'wxapp'){
                    $config['app_id'] = "wx3ff08379ada43557";
                    //$config['key'] = '49ae4cc02384b4510511763791d311e7';
                }
                break;
        }

        return $config;
    }

    /**
     * 小程序实例
     * @return \EasyWeChat\MiniProgram\MiniProgram
     */
    public static function miniprogram()
    {
        return self::getApp('miniProgram');
    }

    /**
     * 支付实例
     * @return mixed
     */
    public static function payment($tpye='payment')
    {
        return self::getApp('payment',$tpye);
    }

    /**
     *
     * @return mixed
     */
    public static function wxapp_pay()
    {
        return self::getApp('app');
    }

    /**
     * 小程序支付回调
     */
    public static function handleNotify()
    {
        $request = request();
        $response = $request->getContent();
        $response = XML::parse($response);
        //info('支付回调：',$response);

//        $response = '{"appid":"wxd056d92701e08bb4","attach":"product",
//"bank_type":"OTHERS","cash_fee":"10","fee_type":"CNY",
//"is_subscribe":"N","mch_id":"1493717222",
//"nonce_str":"5deb9df1b51bc",
//"openid":"oavRH4_8A3WWNeqRMm1k52BmJpzU",
//"out_trade_no":"wx157572248171111461",
//"result_code":"SUCCESS",
//"return_code":"SUCCESS","sign":"69C8CBC6E6FC685D732FF554420EC35E",
//"time_end":"20191207204136","total_fee":"10","trade_type":"JSAPI","transaction_id":"4200000447201912075733470948"}';
//        $response = json_decode($response,true);

        $orderId = $response['out_trade_no'];
        $order = Orders::getByOrderId($orderId);

        if (!$order) {
            Log::error("回调订单数据异常:",$response);
        }
        //回调日志记录
        PayResponseData::record($orderId, $response['attach'], $response);

        $app = MiniProgramService::payment();

        $response = $app->handlePaidNotify(function ($message, $fail) use ($order) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            if (!$order || $order->paid) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {

                    $transactionId = (string)$message['transaction_id'];
                    OrderService::paySuccess($order->order_id, 'weixin', $message['attach'], $transactionId);

                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->notify_fail = array_get($message, 'return_msg');
                    $order->save(); // 保存订单
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            return true; // 返回处理完成
        });

        $response->send(); // return $response;

    }


}
